package com.castle.fortress.admin.temp.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.temp.entity.TempTreeEntity;
import com.castle.fortress.admin.temp.dto.TempTreeDto;
import com.castle.fortress.admin.temp.service.TempTreeService;
import com.castle.fortress.common.utils.ConvertUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.admin.core.annotation.CastleLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.castle.fortress.admin.utils.ExcelUtils;
import javax.servlet.http.HttpServletResponse;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.hutool.core.util.StrUtil;
import com.castle.fortress.common.respcode.BizErrorCode;

/**
 * 生成树示例 控制器
 *
 * @author 
 * @since 2023-08-03
 */
@Api(tags="生成树示例管理控制器")
@Controller
public class TempTreeController {
    @Autowired
    private TempTreeService tempTreeService;

	/**
	 * 生成树示例的分页展示
	 * @param tempTreeDto 生成树示例实体类
	 * @param current 当前页
	 * @param size  每页记录数
	 * @return
	 */
    @CastleLog(operLocation="生成树示例",operType = OperationTypeEnum.QUERY)
	@ApiOperation("生成树示例分页展示")
	@GetMapping("/temp/tempTree/page")
	@ResponseBody
	@RequiresPermissions("temp:tempTree:pageList")
	public RespBody<IPage<TempTreeDto>> pageTempTree(TempTreeDto tempTreeDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
		Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
		Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
		Page<TempTreeDto> page = new Page(pageIndex, pageSize);
			IPage<TempTreeDto> pages = tempTreeService.pageTempTree(page, tempTreeDto);

		return RespBody.data(pages);
	}

    /**
     * 生成树示例的树形展示
     * @param tempTreeDto 生成树示例实体类
     * @return
     */
    @CastleLog(operLocation="生成树示例",operType = OperationTypeEnum.QUERY)
    @ApiOperation("生成树示例分页展示")
    @GetMapping("/temp/tempTree/tree")
    @ResponseBody
    @RequiresPermissions("temp:tempTree:pageList")
    public RespBody<List<TempTreeDto>> treeTempTree(TempTreeDto tempTreeDto){
	    List<TempTreeDto> list = tempTreeService.listTempTree(tempTreeDto);
	    //展示时需要展示到顶级
	    Set<Long> ids=new HashSet<>();
	    for(TempTreeDto s:list){
		    ids.add(s.getId());
	    }
	    List<Long> parentId =new ArrayList<>();
	    List<TempTreeDto> parentList=new ArrayList<>();
	    for(TempTreeDto s:list){
		    if(s.getParentId()!=null&&!ids.contains(s.getParentId())){
			    parentId.add(s.getParentId());
		    }
	    }
	    if(!parentId.isEmpty()){
		    QueryWrapper<TempTreeEntity> wrapper=new QueryWrapper<>();
		    wrapper.in("id",parentId);
		    parentList= ConvertUtil.transformObjList(tempTreeService.list(wrapper),TempTreeDto.class);
		    list.addAll(parentList);
	    }
	    do{
		    parentId =new ArrayList<>();
		    for(TempTreeDto s:parentList){
			    if(s.getParentId()!=null){
				    parentId.add(s.getParentId());
			    }
		    }
		    if(!parentId.isEmpty()){
			    QueryWrapper<TempTreeEntity> wrapper=new QueryWrapper<>();
			    wrapper.in("id",parentId);
			    parentList= ConvertUtil.transformObjList(tempTreeService.list(wrapper),TempTreeDto.class);
			    list.addAll(parentList);
		    }
	    }while(!parentId.isEmpty());
	    return RespBody.data(ConvertUtil.listToTree(list));
    }

    /**
     * 生成树示例的列表展示
     * @param tempTreeDto 生成树示例实体类
     * @return
     */
    @CastleLog(operLocation="生成树示例",operType = OperationTypeEnum.QUERY)
    @ApiOperation("生成树示例列表展示")
    @GetMapping("/temp/tempTree/list")
    @ResponseBody
    public RespBody<List<TempTreeDto>> listTempTree(TempTreeDto tempTreeDto){
        List<TempTreeDto> list = tempTreeService.listTempTree(tempTreeDto);
        return RespBody.data(list);
    }

    /**
     * 生成树示例保存
     * @param tempTreeDto 生成树示例实体类
     * @return
     */
    @CastleLog(operLocation="生成树示例",operType = OperationTypeEnum.INSERT)
    @ApiOperation("生成树示例保存")
    @PostMapping("/temp/tempTree/save")
    @ResponseBody
    @RequiresPermissions("temp:tempTree:save")
    public RespBody<String> saveTempTree(@RequestBody TempTreeDto tempTreeDto){
        if(tempTreeDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        TempTreeEntity tempTreeEntity = ConvertUtil.transformObj(tempTreeDto,TempTreeEntity.class);
	    if(tempTreeEntity.getParentId()!=null){
            TempTreeEntity parent = tempTreeService.getById(tempTreeEntity.getParentId());
		    if(StrUtil.isEmpty(parent.getParents())){
                tempTreeEntity.setParents(parent.getId()+"");
		    }else{
                tempTreeEntity.setParents(parent.getParents()+","+parent.getId());
		    }
	    }
        if(tempTreeService.save(tempTreeEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 生成树示例编辑
     * @param tempTreeDto 生成树示例实体类
     * @return
     */
    @CastleLog(operLocation="生成树示例",operType = OperationTypeEnum.UPDATE)
    @ApiOperation("生成树示例编辑")
    @PostMapping("/temp/tempTree/edit")
    @ResponseBody
    @RequiresPermissions("temp:tempTree:edit")
    public RespBody<String> updateTempTree(@RequestBody TempTreeDto tempTreeDto){
        if(tempTreeDto == null || tempTreeDto.getId() == null || tempTreeDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        TempTreeEntity tempTreeEntity = ConvertUtil.transformObj(tempTreeDto,TempTreeEntity.class);
	    if(tempTreeEntity.getParentId()!=null){
	    	//校验父级是否是子集
            if(tempTreeEntity.getParentId().equals(tempTreeEntity.getId())){
                throw new BizException(BizErrorCode.PARENT_IS_SON_ERROR);
            }
            QueryWrapper<TempTreeEntity> wrapper=new QueryWrapper<>();
            wrapper.like("parents",tempTreeEntity.getId());
			wrapper.eq("id",tempTreeEntity.getParentId());
            List<TempTreeEntity> sons = tempTreeService.list(wrapper);
            if(sons!=null && sons.size()>0){
	            throw new BizException(BizErrorCode.PARENT_IS_SON_ERROR);
            }
            TempTreeEntity parent = tempTreeService.getById(tempTreeEntity.getParentId());
		    if(StrUtil.isEmpty(parent.getParents())){
                tempTreeEntity.setParents(parent.getId()+"");
		    }else{
                tempTreeEntity.setParents(parent.getParents()+","+parent.getId());
		    }
	    }
        if(tempTreeService.updateById(tempTreeEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 生成树示例删除
     * @param id
     * @return
     */
    @CastleLog(operLocation="生成树示例",operType = OperationTypeEnum.DELETE)
    @ApiOperation("生成树示例删除")
    @PostMapping("/temp/tempTree/delete")
    @ResponseBody
    @RequiresPermissions("temp:tempTree:delete")
    public RespBody<String> deleteTempTree(@RequestParam Long id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
	    QueryWrapper<TempTreeEntity> wrapper=new QueryWrapper<>();
	    wrapper.eq("id",id);
	    wrapper.or().like("parents",id);
	    if(tempTreeService.remove(wrapper)) {
            return RespBody.data("删除成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * 生成树示例批量删除
     * @param ids
     * @return
     */
    @CastleLog(operLocation="生成树示例",operType = OperationTypeEnum.DELETE)
    @ApiOperation("生成树示例批量删除")
    @PostMapping("/temp/tempTree/deleteBatch")
    @ResponseBody
    @RequiresPermissions("temp:tempTree:deleteBatch")
    public RespBody<String> deleteTempTreeBatch(@RequestBody List<Long> ids){
        if(ids == null || ids.size()<1){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
	    QueryWrapper<TempTreeEntity> wrapper=new QueryWrapper<>();
	    wrapper.in("id",ids);
	    for(Long d:ids){
		    wrapper.or().like("parents",d);
	    }
	    if(tempTreeService.remove(wrapper)) {
            return RespBody.data("删除成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 生成树示例详情
     * @param id 生成树示例id
     * @return
     */
    @CastleLog(operLocation="生成树示例",operType = OperationTypeEnum.QUERY)
    @ApiOperation("生成树示例详情")
    @GetMapping("/temp/tempTree/info")
    @ResponseBody
    @RequiresPermissions("temp:tempTree:info")
    public RespBody<TempTreeDto> infoTempTree(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        TempTreeEntity tempTreeEntity = tempTreeService.getById(id);
        TempTreeDto tempTreeDto = ConvertUtil.transformObj(tempTreeEntity,TempTreeDto.class);

        return RespBody.data(tempTreeDto);
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation="生成树示例",operType = OperationTypeEnum.EXPORT)
	@PostMapping("/temp/tempTree/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<TempTreeDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<TempTreeDto> list = tempTreeService.listTempTree(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}


}
